﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Emerald.Business.Controllers;
using Emerald.Business;

namespace Emerald.WebSite.Extensions.Handlers
{
    /// <summary>
    /// 
    /// </summary>
    public class ErrorModule : IHttpModule
    {
        private EventController m_eventController;
        private UserController m_userController;

        private EventController EventController
        {
            get
            {
                if (m_eventController == null)
                {
                    m_eventController = new EventController();
                }

                return m_eventController;
            }
        }

        private UserController UserController
        {
            get
            {
                if (m_userController == null)
                {
                    m_userController = new UserController();
                }

                return m_userController;
            }
        }

        #region IHttpModule Members

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.Error += new EventHandler(context_Error);
        }

        #endregion

        private User GetUserByUsername(string username)
        {
            if (String.IsNullOrEmpty(username))
            {
                return null;
            }

            return UserController.GetUserByUsername(username);
        }

        private void context_Error(object sender, EventArgs e)
        {
            Event errorEvent = new Event();

            errorEvent.Type = Event.EventType.Error;
            errorEvent.DateTime = DateTime.Now;
            errorEvent.User = GetUserByUsername(HttpContext.Current.User.Identity.Name);
            errorEvent.Source = this.GetType().FullName;
            errorEvent.Message = HttpContext.Current.Error.Message;
            errorEvent.StackTrace = HttpContext.Current.Error.StackTrace;

            EventController.Insert(errorEvent);
        }
    }
}
